<template>
  <div class="content" v-loading="submitBtn || (!dialogVisibleTemplate && nodeLoading)">
    <div class="scroll-view-box">
      <el-form label-width="120px" :model="formData" :rules="formRules" ref="elFrom" label-position="top">
        <el-form-item label="验收模版" prop="name">
          <el-input v-model="formData.name" placeholder="请输入验收模版" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="验收节点" required>
          <div class="add-node" @click="getNodesList({ type: 'node' })">新增</div>
          <div class="node-box">
            <div class="node-item" v-for="(item, index) in formData.nodes" :key="index">
              <i class="el-icon-error" @click="delNode({ index })"></i>
              <div class="node-header">
                <div class="node-title" :ref="`node-title${index}`" :contenteditable="true" v-html="item.node_name"
                  @focus="divFocus" @blur="divBlur($event, index)"></div>
                <i class="el-icon-edit" @click="nodeFocus(`node-title${index}`)"></i>
              </div>
              <div class="node-conter">
                <div class="null-data" v-if="item.acceptance_criteria.length == 0">
                  <el-empty :image="require('@/assets/icon/null.png')" :image-size="64"
                    description="暂未添加验收标准"></el-empty>
                </div>
                <div class="standard-item" v-for="(row, idx) in item.acceptance_criteria" :key="idx">
                  <div class="standard-top">
                    <div class="standard-title">{{ idx + 1 }}.
                      <div :ref="`standard-title${index}${idx}`" :contenteditable="true" v-html="row.criteria_name"
                        @focus="divFocus" @blur="divBlur($event, index, idx)"></div>
                    </div>

                    <div class="icon-box">
                      <i class="el-icon-edit" @click="nodeFocus(`standard-title${index}${idx}`)"></i>
                      <i class="el-icon-close" @click="delNode({ index, idx })" style="font-size: 16px;"></i>
                    </div>
                  </div>
                  <div class="standard-desc">{{ row.content_type == 1 ? '文本' : '图片视频' }}/{{ row.is_required == 1 ? '必填'
                    :
                    '非必填' }}</div>
                </div>
              </div>
              <div class="node-footer" @click="getNodesList({ type: 'check', index })">
                <i class="el-icon-plus"></i>
                <div class="add-standard">新增验收标准</div>
              </div>
            </div>
          </div>
          <div></div>
        </el-form-item>
        <el-form-item label="进度款节点" prop="pay_node">
          <el-select filterable v-model="formData.pay_node" placeholder="请选择进度款节点" clearable class="input-width">
            <el-option v-for="(item, index) in formData.nodes" :key="index" :label="item.node_name" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="chooseType == 'node' ? '添加验收节点' : '添加验收标准'" :visible.sync="dialogVisibleTemplate" width="850px"
      :before-close="handleClose" :close-on-click-modal="false">
      <div class="scroll-view">
        <el-form :inline="true" :model="bzSearchForm" class="bz-search" v-if="chooseType != 'node'">
          <el-form-item>
            <el-input prefix-icon="el-icon-search" v-model="bzSearchForm.keyword" placeholder="搜索的标准名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              @click="getNodesList({ type: 'check', index: indexOne, childIndex: indexTwo })">查询</el-button>
          </el-form-item>
        </el-form>
        <el-form label-position="left" label-width="80px" :model="formTemplate" ref="ruleFormTemplate"
          class="demo-form-inline">
          <div class="node-box" v-if="chooseType == 'node'">
            <el-checkbox-group v-model="formTemplate.nodeCheckVal">
              <el-checkbox v-for="(item, index) in nodesList" :key="index" :label="item.node_name" border></el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="node-box" v-else style="height: 310px;">
            <el-checkbox-group class="flex fw" v-model="formTemplate.nodeCheckVal">
              <div class="check-item" v-for="(item, index) in nodesList" :key="index">
                <el-checkbox :label="item.node_name">
                  <span class="ellipsis" style="width: 200px;">{{ item.node_name }}</span>
                </el-checkbox>
                <div class="radio-group">
                  <el-radio-group v-model="item.content_type"
                    @change="radioChange($event, item.node_name, 'content_type')">
                    <el-radio :label="1">文本</el-radio>
                    <el-radio :label="2">图片视频</el-radio>
                  </el-radio-group>
                </div>
                <div class="radio-group">
                  <el-radio-group v-model="item.is_required"
                    @change="radioChange($event, item.node_name, 'is_required')">
                    <el-radio :label="1">必填</el-radio>
                    <el-radio :label="2">选填</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer"
        style="display: flex;justify-content: space-between;align-items: center;">
        <span style="font-size: 14px;margin-right: 10px;">已选中 {{ formTemplate.nodeCheckVal.length }}</span>
        <div>
          <el-button type="primary" @click="submitTemplateFunc('ruleFormTemplate')">提交</el-button>
          <el-button @click="handleClose">关闭</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import nodesApi from "@/api/nodesApi"

export default {
  name: 'acceptanceTemplateAdd',
  data() {
    return {
      editType: 'add',
      formData: {
        id: '',
        name: '',
        pay_node: '',
        nodes: [],
      },
      formRules: {
        name: [{ required: true, message: "请输入验收模版", trigger: "change", },],
        pay_node: [{ required: true, message: "请选择进度款节点", trigger: "change", },],
      },
      submitBtn: false,

      // 节点弹窗
      nodeLoading: false,
      chooseType: '',
      dialogVisibleTemplate: false,
      nodesList: [], //节点列表
      oldnodeList: [],
      indexOne: '',
      bzSearchForm: {
        keyword: '',
      },
      formTemplate: {
        nodeCheckVal: [], //节点选中列表
      },

    };
  },
  computed: {
  },
  mounted() {
    let id = this.$route.query.sn
    if (id) {
      this.editType = "edit";
      nodesApi.getTemplateDetail({ template_id: id }).then((res) => {
        console.log(res, "getTemplateDetail");
        if (res.code == 200) {
          let data = res.data
          let formData = {
            id,
            name: res.data.template_name,
            pay_node: '',
            nodes: [],
          }
          data.template_nodes.map((item, index) => {
            if (item.is_payment_review == 1) {
              formData.pay_node = index
            }
            formData.nodes.push({
              node_name: item.node_name,
              remark: item.remark,
              is_payment_review: 2,
              acceptance_criteria: []
            })
            item.children.map(row => {
              formData.nodes[index].acceptance_criteria.push({
                criteria_name: row.node_name,
                content_type: row.content_type,
                is_required: row.is_required
              })
            })
          })
          this.formData = formData
        } else {
          this.$message.error(res.message);
        }
      });
    }
  },
  methods: {
    /**************弹窗相关**************/
    handleClose() {
      if (this.dialogVisibleTemplate) {
        this.dialogVisibleTemplate = false;
        this.bzSearchForm.keyword = '';
        this.formTemplate.nodeCheckVal = [];
        this.oldnodeList = [];
        return;
      }
      this.formTemplate.nodeCheckVal = [];
      this.dialogVisible = false;
    },
    radioChange(e, name, field) {
      let i = this.oldnodeList.findIndex(n => {
        return n.node_name == name;
      })
      this.oldnodeList[i][field] = e;
    },
    // 获取节点列表
    getNodesList(obj) {
      console.log(obj)
      this.nodeLoading = true;
      this.chooseType = obj.type;
      this.indexOne = obj.index;
      let keyword = this.bzSearchForm.keyword;
      nodesApi.getNodesList({
        page: 1,
        num: 9999,
        type: obj.type == 'node' ? 1 : 2,
        keyword
      }).then(res => {
        console.log(res, "节点列表")
        this.nodeLoading = false;
        if (res.code == 200) {
          if (obj.type == 'check') {
            res.data.list.forEach(item => {
              item.content_type = 1;
              item.is_required = 1;
            })
            if (keyword == '') {
              this.oldnodeList = res.data.list;
            }
          }
          this.nodesList = res.data.list;
          this.dialogVisibleTemplate = true;
          this.$nextTick(() => {
            this.$refs['ruleFormTemplate'].clearValidate();
          })
        }
      }).catch(err => {
        this.nodeLoading = false;
      })
    },
    submitTemplateFunc() {
      let formTemplate = this.formTemplate;
      if (!formTemplate.nodeCheckVal.length) {
        this.$message.warning(chooseType == 'node' ? '请勾选验收节点' : '请勾选验收标准');
        return;
      }

      let chooseType = this.chooseType;
      let formData = this.formData

      if (chooseType == 'node') {
        formTemplate.nodeCheckVal.forEach(item => {
          formData.nodes.push({
            node_name: item,
            remark: '',
            is_payment_review: 2,
            acceptance_criteria: []
          })
        })
      } else {
        let oldnodeList = this.oldnodeList;
        let indexOne = this.indexOne;

        formTemplate.nodeCheckVal.forEach(item => {
          let idx = oldnodeList.findIndex(n => {
            return n.node_name == item;
          })
          formData.nodes[indexOne].acceptance_criteria.push({
            // edit_oper: false,
            criteria_name: item,
            content_type: oldnodeList[idx].content_type,
            is_required: oldnodeList[idx].is_required,
          })
        })
      }
      this.handleClose();
    },
    delNode(obj) {
      let index = obj.index
      let idx = obj.idx
      if (idx != undefined) {
        this.formData.nodes[index].acceptance_criteria.splice(idx, 1)
      } else {
        this.formData.nodes.splice(index, 1)
      }
    },

    // 文本改变时事件
    divFocus(e) {
      let obj = e.target;
      if (window.getSelection) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(obj);
        selection.removeAllRanges();
        selection.addRange(range);
      } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(obj);
        textRange.select();
      }
    },
    divBlur(e, index, idx) {
      console.log(e.target.innerHTML, index, idx, 'divBlur')
      let val = e.target.innerHTML
      let nodes = this.formData.nodes
      if (idx == undefined) {
        nodes[index].node_name = val
      } else {
        nodes[index].acceptance_criteria[idx].criteria_name = val
      }
    },
    nodeFocus(name) {
      this.$refs[name][0].focus();
    },

    /**************end**************/
    // 提交
    saveSubmit() {
      this.$refs['elFrom'].validate((valid) => {
        if (valid) {
          let formData = this.formData
          let check = false
          for (let i = 0; i < formData.nodes.length; i++) {
            let item = formData.nodes[i]
            if (i == formData.pay_node) {
              item.is_payment_review = 1
            }
            if (item.acceptance_criteria.length == 0) {
              this.$message.warning(item.node_name + ' 未选择验收标准')
              check = true
              break
            }
          }
          if (check) return
          this.submitBtn = true
          if (this.editType == 'add') {
            nodesApi.addTemplate({
              template_name: formData.name,
              nodes: formData.nodes
            }).then(res => {
              console.log(res, '新增模版')
              if (res.code == 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.error(res.message);
              }
              this.submitBtn = false;
            })
          } else {
            nodesApi.updTemplate({
              template_id: formData.id,
              template_name: formData.name,
              nodes: formData.nodes
            }).then(res => {
              console.log(res, '更新模版')
              if (res.code == 200) {
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.error(res.message);
              }
              this.submitBtn = false;
            })
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";
@import "index.scss";
</style>